from flask import Blueprint, request, session
from flask_restful import Api, Resource
from flask_restful.reqparse import RequestParser

from utils.render import json_detail_render
from webapp.config.api_utils import oper_log, check_auth
from webapp.schema import PlanSchema
from webapp.service.teach_service import PlanService

implan_app = Blueprint('implan_api', __name__, url_prefix='/api/implan')
implan_api = Api(implan_app)

parser = RequestParser()


@implan_api.resource('', '/')
class PlanImportApi(Resource):
    @oper_log('导入教学计划', request)
    @check_auth('plan:add', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        isAllSuccess = True
        isExistPlan = []
        for param in params:
            try:
                schema = PlanSchema()
                curr_plan = schema.load(param, unknown="exclude")
                data = session["user"]
                curr_plan.sub_count = 0
                curr_plan.create_by = data["username"]
                PlanService.create(curr_plan=curr_plan)
            except Exception as e:
                print(e)
                isExistPlan.append(param)
                isAllSuccess = False
                continue
        if isAllSuccess:
            return json_detail_render(0, message="导入成功")
        else:
            strPlan = ''
            for plan in isExistPlan:
                strPlan += plan+','
            return json_detail_render(500, message="{} 等导入计划失败".format(strPlan))